import os, random, datetime, subprocess
import sys
sys.path.append('/opt/sumo/sumo-0.17.1/tools')
import sumolib
import trace

def main():
    print "loading trace file..."
    tt = trace.readTrace('/Users/hezongjian/Documents/texsrc/Traffic/simu/trace/netstate.xml')
    # tt.dump()
    
    # collect all speeds
    speeds = []
    snapshots = tt.getSnapshots()
    for sh in snapshots:
        edges = snapshots[sh].getEdges()
        for rd in edges:
            vehicles = edges[rd].getVehicles()
            for v in vehicles:
                speeds.append( vehicles[v].getSpeed() )
            #end for
        #end for
    #end for
    
    with open('./speed.txt', 'a') as f:
        for s in speeds:
            opt = "%f\r\n" % (s)
            f.write(opt)
    print "speed exported"
    
    # collect all vehicles
    vehiclenumber = []
    snapshots = tt.getSnapshots()
    for sh in snapshots:
        edges = snapshots[sh].getEdges()
        for rd in edges:
            vehicles = edges[rd].getVehicles()
            # remove zero vehicles
            if len(vehicles) > 1: 
                vehiclenumber.append( len(vehicles) )
            #end for
        #end for
    #end for
    with open('./vehicle.txt', 'a') as f:
        for v in vehiclenumber:
            opt = "%d\r\n" % (v)
            f.write(opt)
    print "vehicle exported"

if __name__ == "__main__":
    main()

